/**
 * 类名：点单服务商品管理业务类
 * 备注：负责点单服务商品管理业务逻辑。
 * 作者：rankin
 * 日期：2016/03/10
 */
var CafeCategory = require('../models/CafeCategory');
var CafeGoods = require('../models/CafeGoods');
var Page = require('../models/page');
var User = require('../models/User');

var qiniu = require('../utils/qiniu');
var config = require('../config/settings');

var ObjectID = require('mongodb').ObjectID;
var debug = require('debug')('controller:cafegoods');
var async = require('async');
var _ = require('underscore');


//数据库错误响应
function handleError(err, res) {
    debug('Happend error response fail to client. [%o]', err);
    res.send({success: false, msg: err});
};

module.exports = {

    /**
     * 商品创建页
     * @param req
     * @param res
     */
    to_create: function (req, res) {

        var query = {};
        if (!req.session.permissionMap[4010]) {//没有4010权限，则需要按用户查询
            query.system_user_id = req.session.user._id;
        }

        //获得所有目录
        CafeCategory.find(query).exec().then(function (categories) {

            if (req.session.permissionMap[4010]) {//拥有4010权限，查询所有用户数据
                return User.find().exec().then(function (users) {
                    return Promise.resolve({users: users, categories: categories});
                });
            } else {
                return Promise.resolve({users: [], categories: categories});
            }
        }).then(function (result) {
            //组织成选项列表
            var categoriesOptions = [];
            _.each(result.categories, function (el1, index, list) {
                _.each(result.categories, function (el2, index, list) {
                    //添加二级
                    if (el2.parent_id == el1._id) {
                        categoriesOptions.push({
                            suid: el2.system_user_id,
                            value: el2._id,
                            name: el1.name + '/' + el2.name
                        });
                    }
                });
            });

            res.render('cafe/goods_create', {data: {users: result.users, categories: categoriesOptions}});
        }).error(function (err) {
            handleError(err, res);
        });
    },

    /**
     * 商品创建
     * @param req
     * @param res
     */
    do_create: function (req, res) {

        debug('Got a request to [do_create],request body is [%o].', req.body);

        //获取请求参数
        var category = req.body.category;
        var name = req.body.name;
        var price = req.body.price;
        var note = req.body.note;
        var pic = req.files.pic;
        var suid = req.body.suid;

        //数据格式验证
        if (!name) {    //名称必须不为空
            res.send({success: false, msg: '商品名称必须不为空.'});
            debug('The parameter "name" can not be empty，response fail to client.');
            return;
        }
        if (!category) {    //目录必须不为空
            res.send({success: false, msg: '商品目录必须不为空.'});
            debug('The parameter "category" can not be empty，response fail to client.');
            return;
        }
        if (!price) {    //价格必须不为空
            res.send({success: false, msg: '商品价格必须不为空.'});
            debug('The parameter "price" can not be empty，response fail to client.');
            return;
        }
        if (isNaN(price)) {  //价格必须是数字
            res.send({success: false, msg: '商品价格必须是数字.'});
            debug('The parameter "price" can not be Number，response fail to client.');
            return;
        }
        if (!pic) {    //图片必须不为空
            res.send({success: false, msg: '商品图片必须不为空.'});
            debug('The parameter "price" can not be empty，response fail to client.');
            return;
        }

        //上传七牛
        qiniu.upload('cafe/' + pic.name, pic.path, function (err, ret) {
            if (err) {
                //上传失败
                res.send({success: false, msg: '商品图片上传失败.'});
                debug('The file parameter "pic" cant not upload to qiniu，response fail to client. [%o]', err);
                return;
            }

            debug('The file was uploaded to qiniu，create new CafeGoods to db. qiniu response is [%o].', ret);

            // 商品模型
            var newModel = {
                category_id: category,
                name: name,
                price: price * 100, //保存时以分为单位
                note: note,
                pic_url: config.Domain + ret.key,
                system_user_id: suid ? suid : req.session.user._id,
                create_time: new Date()
            };
            debug('Create a new CafeGoods instance to DB. [%o]', newModel);
            //保存新商品
            CafeGoods.create(newModel, function (err, newDoc) {
                if (err) {
                    handleError(err, res);
                } else {
                    //保存成功，跳转到列表
                    res.redirect('/cafe/goods/list');
                    //res.send({success: true, data: newDoc});
                    debug('The CafeGoods create is successful,response success to client.');
                }
            });
        });
    },
    /**
     * 箱子管理列表页
     * @param req
     * @param res
     */
    list: function (req, res) {

        //获取参数
        var num = req.query.num || 0;
        var category = req.query.category || '';
        var name = req.query.name || '';
        var note = req.query.note || '';

        //设置查询条件
        var page = new Page(num);
        var query = {};

        if (name) {    //设置名称
            query.name = /'+name+'/i;
        }
        if (note) {    //设置备注
            query.note = /'+note+'/i;
        }
        if (!req.session.permissionMap[4010]) {//没有4010权限，则需要按用户查询
            query.system_user_id = req.session.user._id;
        }

        debug('The CafeGoods query is [%o].', query);

        async.waterfall(
            [
                function (callback) {
                    //查询商品数量
                    CafeGoods.count(query, callback);
                },
                function (total, callback) {
                    //查询商品
                    CafeGoods.find(query, null, {skip: page.skipFrom, limit: page.limit}, function (err, goodses) {
                        if (err) {
                            callback(err);
                        } else {
                            callback(null, total, goodses);
                        }
                    });
                },
                function (total, goodses, callback) {
                    if (goodses.length == 0) {
                        return callback(null, {
                            total: 0,
                            goodses: []
                        });
                    }

                    //处理数据
                    _.each(goodses, function (goods, index, list) {
                        //查询二级目录
                        CafeCategory.findOne({_id: ObjectID(goods.category_id)}, function (err, category) {
                            if (err || !category) {
                                handleError(err, res);
                                return;
                            }
                            //查询一级目录
                            CafeCategory.findOne({_id: ObjectID(category.parent_id)}, function (err, parent_category) {
                                if (err || !parent_category) {
                                    handleError(err, res);
                                    return;
                                }
                                //组合一级目录和二级目录
                                goods.category = parent_category.name + '/' + category.name;
                                //最后一个退出循环
                                if (index + 1 == list.length) {
                                    callback(null, {
                                        total: total,
                                        goodses: goodses
                                    });
                                }
                            });
                        });
                    });
                }
            ],
            function (err, result) {
                if (err) {
                    handleError(err, res);
                    return;
                }
                //计算分页
                var pageCount = Math.ceil(result.total / page.limit);
                //响应数据
                res.render('cafe/goods_list', {goodses: result.goodses, pageCount: pageCount});
            }
        )
        ;
    },
    /**
     * 商品编辑页
     * @param req
     * @param res
     */
    to_edit: function (req, res) {

        debug('Got a request to [to_edit],request params is [%o],body is [%o].', req.params, req.body);

        //获得参数
        var goods_id = req.params.id;

        //数据格式验证
        if (!goods_id) {    //ID必须不为空
            res.send({success: false, msg: '商品ID必须不为空.'});
            debug('The parameter "id" can not be empty，response fail to client.');
            return;
        }

        CafeGoods.findOne({_id: ObjectID(goods_id)}, function (err, goods) {

            if (err) {
                handleError(err, res);
                return;
            }

            //获得所有目录
            CafeCategory.find({system_user_id: goods.system_user_id}, function (err, categories) {

                if (err) {
                    handleError(err, res);
                    return;
                }

                //组织成选项列表
                var categoriesOptions = [];
                _.each(categories, function (el1, index, list) {
                    _.each(categories, function (el2, index, list) {
                        //添加二级
                        if (el2.parent_id == el1._id) {
                            categoriesOptions.push({
                                value: el2._id,
                                name: el1.name + '/' + el2.name
                            });
                        }
                    });
                });

                //响应数据
                res.render('cafe/goods_edit', {
                    data: {
                        goods: goods,
                        categories: categoriesOptions
                    }
                });
            });
        });

    },
    /**
     * 商品编辑
     * @param req
     * @param res
     */
    do_edit: function (req, res) {

        debug('Got a request to [do_edit],request params is [%o],body is [%o].', req.params, req.body);

        //获取请求参数
        var goods_id = req.params.id;
        var category = req.body.category;
        var name = req.body.name;
        var price = req.body.price;
        var note = req.body.note;
        var pic = req.files.pic;

        //数据格式验证
        if (!goods_id) {    //ID必须不为空
            res.send({success: false, msg: '商品ID必须不为空.'});
            debug('The parameter "id" can not be empty，response fail to client.');
            return;
        }
        if (!name) {    //名称必须不为空
            res.send({success: false, msg: '商品名称必须不为空.'});
            debug('The parameter "name" can not be empty，response fail to client.');
            return;
        }
        if (!category) {    //目录必须不为空
            res.send({success: false, msg: '商品目录必须不为空.'});
            debug('The parameter "category" can not be empty，response fail to client.');
            return;
        }
        if (!price) {    //价格必须不为空
            res.send({success: false, msg: '商品价格必须不为空.'});
            debug('The parameter "price" can not be empty，response fail to client.');
            return;
        }
        if (isNaN(price)) {  //价格必须是数字
            res.send({success: false, msg: '商品价格必须是数字.'});
            debug('The parameter "price" can not be Number，response fail to client.');
            return;
        }

        if (pic) {
            //上传七牛
            qiniu.upload('cafe/' + pic.name, pic.path, function (err, ret) {
                if (err) {
                    //上传失败
                    res.send({success: false, msg: '商品图片上传失败.'});
                    debug('The file parameter "pic" cant not upload to qiniu，response fail to client. [%o]', err);
                    return;
                }

                debug('The file was uploaded to qiniu，create new CafeGoods to db. qiniu response is [%o].', ret);

                //更新商品
                update(config.Domain + ret.key);
            });
        } else {
            update('');
        }

        function update(pic_url) {

            debug('Edit a CafeGoods instance to DB.');

            //保存新商品
            CafeGoods.findOne({_id: ObjectID(goods_id)}, function (err, doc) {
                if (err) {
                    handleError(err, res);
                } else {

                    // 更新字段
                    doc.category_id = category;
                    doc.name = name;
                    doc.price = price * 100; //保存时以分为单位
                    doc.note = note;
                    if (pic_url) {
                        doc.pic_url = pic_url;
                    }

                    //更新
                    doc.save(function (err) {
                        if (err) {
                            handleError(err, res);
                            return;
                        }
                        //保存成功，跳转到列表
                        res.redirect('/cafe/goods/list');
                        debug('The CafeGoods edit is successful,response success to client.');

                    });
                }
            });
        }
    },
    /**
     * 删除商品
     * @param req
     * @param res
     */
    remove: function (req, res) {

        debug('Got a request to [do_edit],request params is [%o],body is [%o].', req.params, req.body);

        //获取请求参数
        var goods_id = req.params.id;

        //数据格式验证
        if (!goods_id) {    //ID必须不为空
            res.send({success: false, msg: '商品ID必须不为空.'});
            debug('The parameter "id" can not be empty，response fail to client.');
            return;
        }

        //查询商品
        CafeGoods.findOne({_id: ObjectID(goods_id)}, function (err, doc) {
            if (err) {
                handleError(err, res);
                return;
            }

            //判断商品是否存在
            if (!doc) {//查询不到商品
                res.send({success: false, msg: '商品ID查询不到商品.'});
                debug('The parameter "id" do not exists in DB，response fail to client.');
                return;
            }

            //删除商品
            doc.remove(function (err) {
                if (err) {
                    handleError(err, res);
                    return;
                }
                //删除商品成功
                res.redirect('/cafe/goods/list');
                debug('The CafeGoods was deleted，response succesfull to client.');
            });
        });
    }
};

